#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
角色申请API
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from backend.models.role_application import RoleApplication
from backend.models.role import Role
from backend.models.user import User
from backend.models.user_role import UserRole
from backend.infrastructure.database import db
from backend.decorators.auth_decorators import require_roles, admin_required
from backend.services.unified_log_service import log_service
from datetime import datetime
import json

role_application_api = Blueprint('role_application_api', __name__)

@role_application_api.route('/api/role-applications', methods=['POST'])
@jwt_required()
def apply_role():
    """申请角色提升"""
    try:
        current_user_id = get_jwt_identity()
        data = request.get_json()
        
        role_id = data.get('role_id')
        reason = data.get('reason', '').strip()
        attachments = data.get('attachments', [])
        
        if not role_id:
            return jsonify({
                'success': False,
                'message': '角色ID不能为空'
            }), 400
        
        if not reason:
            return jsonify({
                'success': False,
                'message': '申请理由不能为空'
            }), 400
        
        # 验证角色存在
        role = Role.query.get(role_id)
        if not role or role.status != 'active':
            return jsonify({
                'success': False,
                'message': '角色不存在或已禁用'
            }), 400
        
        # 检查用户是否已有该角色
        existing_role = UserRole.query.filter_by(
            user_id=current_user_id,
            role_id=role_id
        ).first()
        if existing_role:
            return jsonify({
                'success': False,
                'message': '您已拥有该角色'
            }), 400
        
        # 检查是否已有待处理的申请
        pending_application = RoleApplication.query.filter_by(
            user_id=current_user_id,
            role_id=role_id,
            status='pending'
        ).first()
        if pending_application:
            return jsonify({
                'success': False,
                'message': '您已有该角色的待处理申请'
            }), 400
        
        # 创建申请
        application = RoleApplication(
            user_id=current_user_id,
            role_id=role_id,
            reason=reason,
            attachments=json.dumps(attachments) if attachments else None,
            status='pending'
        )
        db.session.add(application)
        db.session.commit()
        
        # 记录日志
        log_service.log_operation(
            user_id=current_user_id,
            action='ROLE_APPLICATION_CREATE',
            table_name='role_applications',
            record_id=application.id,
            details=f'申请角色: {role.name}'
        )
        
        return jsonify({
            'success': True,
            'data': application.to_dict(),
            'message': '申请提交成功，请等待管理员审核'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'申请失败: {str(e)}'
        }), 500

@role_application_api.route('/api/role-applications', methods=['GET'])
@jwt_required()
def get_role_applications():
    """获取角色申请列表"""
    try:
        current_user_id = get_jwt_identity()
        
        # 获取查询参数
        status = request.args.get('status')
        user_id = request.args.get('user_id')
        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('per_page', 20))
        
        # 构建查询
        query = RoleApplication.query
        
        # 普通用户只能查看自己的申请
        from flask_jwt_extended import get_jwt
        claims = get_jwt()
        user_roles = claims.get('roles', [])
        
        if 'admin' not in user_roles:
            query = query.filter(RoleApplication.user_id == current_user_id)
        elif user_id:
            query = query.filter(RoleApplication.user_id == user_id)
        
        if status:
            query = query.filter(RoleApplication.status == status)
        
        # 按创建时间倒序
        query = query.order_by(RoleApplication.created_at.desc())
        
        # 分页
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        applications = [app.to_dict() for app in pagination.items]
        
        return jsonify({
            'success': True,
            'data': {
                'applications': applications,
                'total': pagination.total,
                'pages': pagination.pages,
                'current_page': page,
                'per_page': per_page
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'查询失败: {str(e)}'
        }), 500

@role_application_api.route('/api/role-applications/<int:application_id>/review', methods=['POST'])
@admin_required
def review_application(application_id):
    """审核角色申请"""
    try:
        current_user_id = get_jwt_identity()
        data = request.get_json()
        
        action = data.get('action')  # approve 或 reject
        review_reason = data.get('review_reason', '').strip()
        
        if action not in ['approve', 'reject']:
            return jsonify({
                'success': False,
                'message': '审核操作必须是approve或reject'
            }), 400
        
        # 查找申请
        application = RoleApplication.query.get(application_id)
        if not application:
            return jsonify({
                'success': False,
                'message': '申请不存在'
            }), 404
        
        if application.status != 'pending':
            return jsonify({
                'success': False,
                'message': '该申请已被处理'
            }), 400
        
        # 更新申请状态
        application.status = 'approved' if action == 'approve' else 'rejected'
        application.reviewer_id = current_user_id
        application.review_reason = review_reason
        application.review_time = datetime.utcnow()
        
        # 如果通过，分配角色
        if action == 'approve':
            # 检查用户是否已有该角色
            existing_role = UserRole.query.filter_by(
                user_id=application.user_id,
                role_id=application.role_id
            ).first()
            
            if not existing_role:
                user_role = UserRole(
                    user_id=application.user_id,
                    role_id=application.role_id
                )
                db.session.add(user_role)
        
        db.session.commit()
        
        # 记录日志
        log_service.log_operation(
            user_id=current_user_id,
            action=f'ROLE_APPLICATION_{action.upper()}',
            table_name='role_applications',
            record_id=application.id,
            details=f'审核角色申请: {application.role.name}, 结果: {action}, 理由: {review_reason}'
        )
        
        return jsonify({
            'success': True,
            'data': application.to_dict(),
            'message': f'审核完成: {"通过" if action == "approve" else "拒绝"}'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'审核失败: {str(e)}'
        }), 500

@role_application_api.route('/api/roles/available', methods=['GET'])
@jwt_required()
def get_available_roles():
    """获取可申请的角色列表"""
    try:
        current_user_id = get_jwt_identity()
        
        # 获取用户当前角色
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({
                'success': False,
                'message': '用户不存在'
            }), 404
        
        current_role_ids = [role.id for role in user.roles]
        
        # 获取可申请的角色（除了已有的和admin角色）
        available_roles = Role.query.filter(
            ~Role.id.in_(current_role_ids),
            Role.name != 'admin',  # admin角色不允许申请
            Role.status == 'active'
        ).all()
        
        roles_data = []
        for role in available_roles:
            # 检查是否有待处理申请
            pending_app = RoleApplication.query.filter_by(
                user_id=current_user_id,
                role_id=role.id,
                status='pending'
            ).first()
            
            role_dict = role.to_dict()
            role_dict['has_pending_application'] = pending_app is not None
            roles_data.append(role_dict)
        
        return jsonify({
            'success': True,
            'data': roles_data
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'查询失败: {str(e)}'
        }), 500
